/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lansupportclient;

import ObjectHandler.LanSupportMessage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileSystemView;

/**
 *
 * @author Quan
 */
public class LanSupportClient extends javax.swing.JFrame {

    private String serverIp;
    private int serverListenPort = 1989;
    private Socket sendSocket;
    private Socket listenSocket;
    public static final int CloseNumber = 13;
    private boolean debug = true;
    private Support.WriteString writeString;
    private lansupportclient.FrameChat frameChat;
    private lansupportclient.FrameMessageFromServer frameMessageFromServer;

    /**
     * Creates new form LanSupportClient
     */
    public LanSupportClient() {
        initComponents();
        writeString = new Support.WriteString(debug);

//        System.out.println("--------------");
//        try {
//            Runtime runtime = Runtime.getRuntime();
//            Process process = runtime.exec("cmd /c C:\\intel && dir");
//
//
//            BufferedReader reader3 = new BufferedReader(
//                    new InputStreamReader(process.getErrorStream()));
//            String out;
//            boolean error = false;
//            while ((out = reader3.readLine()) != null) {
//                error = true;
//                System.out.println(out+" error");
//            }
//
//
//
//            BufferedReader reader = new BufferedReader(
//                    new InputStreamReader(process.getInputStream()));
//            while ((out = reader.readLine()) != null) {
//                System.out.println(out);
//            }
//        } catch (IOException ex) {
//            Logger.getLogger(ShellCmd.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }

    public void SaveFile(byte[] file_content) {
        FileSystemView filesys = FileSystemView.getFileSystemView();
        JFileChooser fileChooser = new JFileChooser(filesys.getHomeDirectory());
        int result = fileChooser.showSaveDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            try {
                try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {
                    fileOutputStream.write(file_content);
                }
            } catch (IOException ex) {
                Logger.getLogger(LanSupportClient.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void SendScreenHot(byte[] file) {
        LanSupportMessage lanSupportMessage = new LanSupportMessage(LanSupportMessage.ClientScreenshotType);
        lanSupportMessage.setData(file);
        lanSupportMessage.Send(sendSocket);
    }

    public void SendScreen(byte[] file) {
        LanSupportMessage lanSupportMessage = new LanSupportMessage(LanSupportMessage.ViewScreenImage);
        lanSupportMessage.setData(file);
        lanSupportMessage.Send(sendSocket);
    }

    private String ReceiveString(Socket socket) throws IOException {
        InputStreamReader receiver = new InputStreamReader(new BufferedInputStream(socket.getInputStream()), "UTF-8");
        StringBuilder stringBuilder = new StringBuilder();
        int c;
        while ((c = receiver.read()) != CloseNumber) {
            stringBuilder.append((char) c);
        }
        return stringBuilder.toString();
    }

    private void SendString(Socket socket, String messages) throws IOException {
        OutputStreamWriter sender = new OutputStreamWriter(socket.getOutputStream());
        sender.write(messages + (char) CloseNumber);
        sender.flush();
    }

    public void AddMessage(String message) {
        ShowFrameChat();
        frameChat.AddMessage(message);
    }

    public void ShowFrameChat() {
        if (frameChat == null) {
            frameChat = new FrameChat(this.sendSocket);
        }
        frameChat.setVisible(true);
    }

    public void ShowMessageFromServer(String message) {
        if (frameMessageFromServer == null) {
            frameMessageFromServer = new FrameMessageFromServer();
        }
        frameMessageFromServer.setVisible(true);
        frameMessageFromServer.ShowMessage(message);
    }

    private void CloseForm() {
        LanSupportMessage lanSupportMessage = new LanSupportMessage(LanSupportMessage.CloseConnection);
        lanSupportMessage.Send(sendSocket);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jFormattedTextField1 = new javax.swing.JFormattedTextField();
        jTextField1 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Lan Support Client");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jButton1.setText("Connect");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jFormattedTextField1.setText("127.0.0.1");

        jTextField1.setText("1989");

        jLabel2.setText("Ip server");

        jLabel3.setText("Port");

        jMenu1.setText("File");

        jMenuItem1.setText("Chat");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuItem2.setText("Send file to Server");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem3.setText("Exit");
        jMenu1.add(jMenuItem3);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(82, 82, 82)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(166, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        this.ShowFrameChat();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        CloseForm();
        try {
            if (sendSocket != null && sendSocket.isConnected()) {
                sendSocket.close();
            }
            if (listenSocket != null && listenSocket.isConnected()) {
                listenSocket.close();
            }
        } catch (IOException ex) {
            Logger.getLogger(LanSupportClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formWindowClosing

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        this.serverIp = jFormattedTextField1.getText();
        this.serverListenPort = Integer.valueOf(jTextField1.getText());

        try {
            //connect to server
            Socket socket = new Socket(InetAddress.getByName(serverIp), serverListenPort);
            writeString.WriteLine("Sent request to Server at port " + serverListenPort);

            //create client send socket
            int randomPort = Integer.valueOf(ReceiveString(socket));
            writeString.WriteLine("Received messages connection will change port to " + randomPort);

            //init send socket
            System.out.println("Send request to server at port " + randomPort);
            this.sendSocket = new Socket(InetAddress.getByName(serverIp), randomPort);

            Integer clientRandomPort = (int) (Math.random() * 10000);
            SendString(sendSocket, clientRandomPort.toString());

            //init listen socket
            writeString.WriteLine("Listening at port " + clientRandomPort);
            ServerSocket serverSocket = new ServerSocket(clientRandomPort);
            this.listenSocket = serverSocket.accept();
            writeString.WriteLine("Connected!");

            Runnable runnable = new ClientListener(listenSocket, sendSocket, this);
            Thread thread = new Thread(runnable);
            thread.start();
        } catch (IOException | NumberFormatException e) {
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jMenuItem2ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JFormattedTextField jFormattedTextField1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
